using System.Data;
using System.Linq;
using System.Xml.Linq;

namespace Code5Systems.FormMaster.Business
{

	public partial class FormController
	{
		
		//Return a FormControlInfo Object for the cell given the row and column in the table
		public FormControlInfo GetFormControlInfo(FormInfo objFormInfo, string row, string col, bool allPages = true)
		{
			FormControlInfo objFormControlInfo = null;
			XElement xControl = default(XElement);
			
			XDocument xDoc = XDocument.Parse(objFormInfo.CurrentPage.PageData);
			
			xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") 
						where c.Attributes("TableRow").First().Value == row 
						&& c.Attributes("TableCol").First().Value == col 
						select c).FirstOrDefault();
			
			if (xControl != null)
			{
				objFormControlInfo = GetFormControlInfo(xControl);
			}
			
			return objFormControlInfo;
			
		}
		
		//Return a FormControlInfo Object by Control ID
		public FormControlInfo GetFormControlInfo(FormInfo objFormInfo, string ctrlID)
		{
			FormControlInfo objFormControlInfo = null;
			XElement xControl = default(XElement);
			
			XDocument xDoc = XDocument.Parse(objFormInfo.CurrentPage.PageData);
			xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") where c.Attributes("ID").First().Value == ctrlID select c).FirstOrDefault();
			
			if (xControl != null)
			{
				objFormControlInfo = GetFormControlInfo(xControl);
			}
			
			return objFormControlInfo;
			
		}
		
		public FormControlInfo GetFormControlInfo(string ctrlID)
		{
			FormControlInfo objFormControlInfo = null;
			XElement xControl = default(XElement);
			
			XDocument xDoc = XDocument.Parse(this.FormInfo.CurrentPage.PageData);
			xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") where c.Attributes("ID").First().Value == ctrlID select c).FirstOrDefault();
			
			if (xControl == null)
			{
				foreach (FormPageInfo page in this.Pages)
				{
					xDoc = XDocument.Parse(page.PageData);
					xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") where c.Attributes("ID").First().Value == ctrlID select c).FirstOrDefault();
					if (xControl != null)
					{
						break;
					}
				}
			}
			
			if (xControl != null)
			{
				objFormControlInfo = GetFormControlInfo(xControl);
			}
			
			return objFormControlInfo;
			
		}
		
	}
	
}
